<!-- 临空时间组件 -->
<template>
  <el-dialog 
    v-el-drag-dialog="{drag: true, full: false, resize: false}"
    :visible="true"
    :close-on-click-modal="false"
    @close="closeMd"
    width="1000px"
  >
    <template slot="title"><span>{{ goDate | time('yyyy年MM月dd号') }} 临空时间设置</span></template>

    <p class="warning-tip">注意：当前订单时间[{{myData.stime}} - {{myData.etime}}]，空闲起止时间必须在该时间范围内。</p>

    <el-form 
      :model="fm.ps" 
      :ref="fm.fname" 
      :label-width="'auto'" 
      :inline="true"
      @keyup.enter.native="onSubmit"
    >
      <el-form-item
        label="起"
        prop="stime"
        :label-width="'40px'"
        :rules="[
          {required: true, message: '请选择开始时间', trigger: 'blur'}
        ]">
        <el-time-select
          v-model="fm.ps.stime"
          :picker-options="{
            start: myData.stime,
            step: '00:05',
            end: myData.etime,
            maxTime: fm.maxTime
          }"
          placeholder="开始时间"
          style="width: 110px;"
          @change="onStimeChange">
        </el-time-select>
      </el-form-item>

      <el-form-item
        label="止"
        prop="etime"
        :label-width="'40px'"
        :rules="[
          {required: true, message: '请选择结束时间', trigger: 'blur'}
        ]"
      >
        <el-time-select
          v-model="fm.ps.etime"
          :picker-options="{
            start: myData.stime,
            step: '00:05',
            end: myData.etime,
            minTime: fm.minTime
          }"
          placeholder="结束时间"
          style="width: 110px;"
        >
        </el-time-select>
      </el-form-item>

      <el-form-item
        label="停靠位置"
        prop="stopPoint.name"
        :rules="[
          {required: true, message: '请选择停靠位置'}
        ]"
      >
        <el-select 
          v-model="fm.ps.stopPoint.name" 
          placeholder="请选择停靠位置"
        >
          <el-option-group
            v-for="g in myData.posList"
            :key="g.label"
            :label="g.label"
          >
            <el-option
              v-for="(it, index) in g.options"
              :key="index"
              :label="it.name"
              :value="it.name"
              @click.native="setStopPoint(it)"
            >
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-form-item
        label="返回位置"
        prop="backPoint.name"
        :rules="[
          {required: true, message: '请选择返回位置'}
        ]"
      >
        <el-select 
          v-model="fm.ps.backPoint.name" 
          placeholder="请选择返回位置"
        >
          <el-option-group
            v-for="g in myData.posList"
            :key="g.label"
            :label="g.label"
          >
            <el-option
              v-for="(it, index) in g.options"
              :key="index"
              :label="it.name"
              :value="it.name"
              @click.native="setBackPoint(it)"
            >
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :disabled="fm.sb.load" @click="onSubmit">{{fm.sb.text}}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20" style="padding: 0px 10px 0px 10px;margin-bottom: 10px;">
      <el-table
        :data="resList"
        :border="true" 
        style="width: 100%;"
      >
        <el-table-column
          type="index"
          width="50"
          label="行号"
          :resizable="false"
        >
        </el-table-column>

        <el-table-column
          prop="stime"
          label="开始时间"
          :resizable="false"
          width="70"
        >
        </el-table-column>

        <el-table-column
          prop="etime"
          label="结束时间"
          :resizable="false"
          width="70"
        >
        </el-table-column>

        <el-table-column
          prop="stopPoint.name"
          label="停靠位置">
        </el-table-column>

        <el-table-column
          prop="backPoint.name"
          label="返回位置">
        </el-table-column>

        <el-table-column
          prop="oper"
          type="index"
          label="操作"
          width="110"
          align="center"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-button 
              v-if="fm.ps.no == scope.$index+''"
              type="warning"
              size="mini"
              @click="cancelEdit(scope.$index, scope.row)"
            >取消编辑</el-button>

            <div v-else>
              <el-button 
                title="删除" 
                type="danger" 
                icon="el-icon-delete" 
                circle 
                @click="delObj(scope.$index, scope.row)"
              ></el-button>

              <el-button 
                title="编辑" 
                type="warning" 
                icon="el-icon-edit" 
                circle 
                @click="editObj(scope.$index, scope.row)"
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div style="text-align: center; padding: 10px 0;">
        <el-button type="primary" @click="saveResDat">确 定</el-button>
      </div>
    </el-row>
  </el-dialog>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog';
import * as orderService from '@/api/services/order.service';

export default {
  name: 'EmptyTimes',
  directives: { elDragDialog },
  props: [ 'myData' ],
  data() { 
    return {
      fm: {
        fname: 'emptyTimesFm',
        sb: { load: false, text: '保存' },
        ps: {
          no: '',                   // 编辑id
          stime: '',                // 开始时间
          etime: '',                // 结束时间
          stopPoint: {name: ''},    // 停靠位置
          backPoint: {name: ''}     // 返回位置  
        },
        // 最小时间
        minTime: this.myData.stime,
        // 最大时间
        maxTime: this.myData.etime,
      },
      goDate: this.myData.date, // 出发日期
      resList: []        // 结果数据
    }
  },
  created(){
    console.log('传入的父级数据', this.myData);

    // 存在-临空设置
    let emptyTimes = this.myData.order.freeTimes;
    if(emptyTimes.length > 0){
      emptyTimes.forEach((it, index) => {
        this.resList.push({
          // 编号
          no: index+'',
          // 开始时间
          stime: it.freeStime.substr(11, 5),
          // 结束时间
          etime: it.freeEtime.substr(11, 5),
          // 停靠地点
          stopPoint: {
            // 停靠地点自定义id
            id: index + 1 + "",
            // 区域
            area: `${it.stayPoint.city}-${it.stayPoint.county}`,
            // 地址详情 成都市 武侯区 天府广场
            address: it.stayPoint.address,
            // 地址简称 天府广场
            name: it.stayPoint.address.split(" ")[1],
            // 地点坐标 140.xxxxxx,30.xxxxxx
            lnglat: it.stayPoint.lngLat,
            // 是否是站点 true-是 false-不是
            isSta: it.stayPoint.isSta == 1 ? true : false,
          },
          // 返回地点
          backPoint: {
            // 返回地点自定义id
            id: index + 2 + "",
            // 区域
            area: `${it.returnPoint.city}-${it.returnPoint.county}`,
            // 地址详情 成都市 武侯区 天府广场
            address: it.returnPoint.address,
            // 地址简称 天府广场
            name: it.returnPoint.address.split(" ")[1],
            // 地点坐标 140.xxxxxx,30.xxxxxx
            lnglat: it.returnPoint.lngLat,
            // 是否是站点 true-是 false-不是
            isSta: it.returnPoint.isSta == 1 ? true : false,
          }
        });
      });
    }
  },
  methods:{
    closeMd(){// 关闭弹框
      const that = this;

      that.$emit('getMdState', {state: false});
    },
    // 开始时间-改变-事件
    onStimeChange(e){
      // 设置结束时间的最小时间为开始时间
      if(e) this.fm.minTime = e;
    },
    // 设置-停靠位置
    setStopPoint(o){
      let sp = this.U.scopy(o);
      this.fm.ps.stopPoint = sp;
    },
    // 设置-返回位置
    setBackPoint(o){
      let bp = this.U.scopy(o);
      this.fm.ps.backPoint = bp;
    },
    /**
     * 验证-欲添加的起止时间是否与已有的起止时间交叉
     * obj-交叉对象 false-不交叉
     * @param index 排除的编号
     */
    isTimeCross(index){
      const that = this, goDate = that.goDate, ps = that.fm.ps;

      if(that.resList.length == 0) return false;

      // 欲添加的起止时间
      let st = that.U.str2date(goDate+' '+ps.stime).getTime();
      let et = that.U.str2date(goDate+' '+ps.etime).getTime();

      // 已存在的起止时间数组
      let obj = null;
      that.resList.find((it, i) => {
        if(index != i+''){// 不验证此编号对象
          let stime = that.U.str2date(goDate+' '+it.stime).getTime();
          let etime = that.U.str2date(goDate+' '+it.etime).getTime();

          if(etime >= st && stime <= et) obj = {...it, no: i+''};
        }
      });
      
      return obj ? obj : false;
    },
    onSubmit(){// 保存-单条临空时间数据
      const that = this, goDate = that.goDate, ps = that.fm.ps;

      that.$refs[that.fm.fname].validate((valid) => {
        if (!valid) {
          return false; 
        }else{
          // 1.开始时间必须小于结束时间
          let st = that.U.str2date(goDate+' '+ps.stime);
          let et = that.U.str2date(goDate+' '+ps.etime);
          if(st.getTime() >= et.getTime()) {
            that.U.qerror('开始时间不能大于结束时间');
          }else{
            let is = that.isTimeCross(ps.no);
            if(is != false){
              that.U.qerror(`欲添加的起止时间与[第${parseInt(is.no)+1}行]的起止时间有冲突`);
            }else{
              // 深拷贝一份，防止双向绑定
              let json = that.U.scopy(ps);
              if(json.no){// 编辑
                // 替换指定行
                that.resList.splice(parseInt(json.no), 1, json);

                that.fm.ps = {
                  no: '',                   // 编辑编号
                  stime: '',                // 开始时间
                  etime: '',                // 结束时间
                  stopPoint: {name: ''},    // 停靠位置
                  backPoint: {name: ''}     // 返回位置  
                }
              }else{// 新增
                that.resList.push(json);

                // 清空起止时间
                ps.stime = '';
                ps.etime = '';
              }
            }
          }
        }
      });
    },
    /**
     * 删除-按钮回调
     * @param i 下标
     * @param row 行数据对象
     */
    delObj(i, row){
      this.resList.splice(i, 1);
    },
    /**
     * 编辑-按钮回调
     * @param i 下标
     * @param row 行数据对象
     */
    editObj(i, row){
      // 深拷贝一份，防止双向绑定
      let json = this.U.scopy(row);
      this.fm.ps = json;
      this.fm.ps.no = i+'';
    },
    /**
     * 取消编辑-按钮回调
     * @param i 下标
     * @param row 行数据对象
     */
    cancelEdit(){
      const that = this, ps = that.fm.ps;

      that.fm.ps = {
        no: '',                   // 编辑编号
        stime: '',                // 开始时间
        etime: '',                // 结束时间
        stopPoint: {name: ''},    // 停靠位置
        backPoint: {name: ''}     // 返回位置  
      }
    },
    saveResDat(){// 保存结果
      const that = this, U = that.U;

      if(that.resList.length == 0) {
        if(that.myData.order && that.myData.order.freeTimes.length > 0){// 修改
          U.qconfim(`确定<span class="c-red">删除所有临空时间设置</span>？`).then(r => {
            if(r){
                let ps = {
                  orderNum: that.myData.orderNum,
                  freeInfo: [],
                };
                orderService.setEmptyTime(ps).then(res => {
                  if (!res || res.code != 1) {
                    U.qerror(res.msg);
                  } else {
                    U.qsuccess(res.msg);

                    that.closeMd();

                    // 调用父组件方法-重新加载数据
                    that.$emit('reloadDg');
                  }
                });
            }
          });
        }else{// 添加
          that.U.qerror('至少添加一条数据');
        }
      }else{
        // console.log('临空设置结果', that.resList);

        let loading = U.qloading("请稍后...");

        // 请求接口，为订单保存临空设置
        let freeInfo = []; // 临空时间
        that.resList.forEach(it => {
          freeInfo.push({
            // 设置临空时间的每日行程id
            dayId: that.myData.dayId,
            // 临空信息id,新增默认为0
            freeId: 0,
            // 临空开始时间
            freeStime: `${that.goDate} ${it.stime}`,
            // 临空结束时间
            freeEtime: `${that.goDate} ${it.etime}`,
            // 停靠位置
            freeSpoint: `${it.stopPoint.area.split('-')[1]} ${it.stopPoint.name}=${it.stopPoint.lnglat}=${it.stopPoint.area}`,
            // 返回位置
            freeEpoint: `${it.backPoint.area.split('-')[1]} ${it.backPoint.name}=${it.backPoint.lnglat}=${it.backPoint.area}`,
          });
        });

        let ps = {
          orderNum: that.myData.orderNum,
          freeInfo: freeInfo
        };
        orderService.setEmptyTime(ps).then(res => {
          U.qclose(loading);

          if (!res || res.code != 1) {
            U.qerror(res.msg);
          } else {
            U.qsuccess(res.msg);

            that.closeMd();

            // 调用父组件方法-重新加载数据
            that.$emit('reloadDg');
          }
        });
      }
    }
    
  }
}
</script>

<style lang="less" scoped>
.warning-tip{
  margin: 0;
  color: #ff6300;
  padding-bottom: 5px;
  margin-bottom: 5px;
  border-bottom: 1px solid #efefef;
}
.res-list{
  padding: 5px;
  border: 1px solid #efefef;
  border-radius: 5px;
  min-height: 100px;
  margin-top: 0;
}
</style>